<template>
  <div class="bigbox">
    <!-- 左侧盒子 -->
    <div class="leftbox" ref="TreeBoxrefs">
      <!-- 搜索框 -->
       <div class="input">
        <el-input v-model="textvalue"  size="small" placeholder="单行输入"></el-input>
      </div>
       <div class="listbox">
        <el-tree
          ref="tree"
          :props="props"
          node-key="id"
          :highlight-current="true"
          @node-click="attree"
          :filter-node-method="filterNode"
          :data="array">
        </el-tree>
       </div>
    </div>
    <!-- 右侧盒子 -->
    <div class="rightbox">
      <!--搜索栏 -->
      <div class="topbox" :style="{height:isheight+'px'}">
        <el-form :model="form" ref="form" :inline="true" label-position="right" label-width="70px" onsubmit="return false">
          <el-col :span="6">
            <el-form-item label="设备名称">
              <el-input v-model="form.deviceName" size="small" style="width: 170px;"></el-input>
            </el-form-item>
          </el-col>
          <el-col  :span="6">
            <el-form-item label="设备类型">
              <el-select v-model="form.deviceType"  clearable  size="small" style="width: 170px;">
                <el-option label="网关" value="Gateway" class="dengji"></el-option>
                <el-option label="表计" value="Meter" class="dengji"></el-option>
                <el-option label="通讯表计" value="CommMeter" class="dengji"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="网关地址">
              <el-input v-model="form.deviceTag" size="small" style="width: 170px;"></el-input>
            </el-form-item>
          </el-col>
            <template v-if="isshow">
              <el-col  :span="6">
            <el-form-item label="采集通道">
              <el-select v-model="form.channelTag" clearable  size="small" style="width: 170px;">
                <el-option v-for="(item,index) in tongdaolist" :key="index" :label="item.text" :value="item.value" class="dengji"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col  :span="18">
            <el-form-item label="是否启用" style="margin-top: 10px;">
              <el-select v-model="form.enabled"  clearable style="width: 170px;" size="small" >
                <el-option label="是" value="true" class="dengji"></el-option>
                <el-option label="否" value="false" class="dengji"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
            </template>
          <el-col :span="6">
            <el-form-item>
              <div style="text-align: right !important;" :style="{'margin-top':isshow?'10px':''}">
              <button  class="button" style="color: black;" @click="chongzhi">重置</button>
              <button  class="button chaxun" @click="submit">查询</button>
              <button type="button" v-if="isshow" class="shou" @click="zedie" style=" cursor: pointer;">收起 <i class="el-icon-arrow-up"></i> </button>
              <button type="button" v-else class="shou" @click="zedie" style=" cursor: pointer;">展开 <i class="el-icon-arrow-down"></i> </button>
            </div>
            </el-form-item>
          </el-col>
        </el-form>
        <!-- <button class="button" >查询</button> -->
      </div>
      <div class="buttombox" ref="tableBox" :style="{height: `calc(${num}% - ${number}px)`}">
        <!-- 文字按钮 -->
        <div class="text">
          <div>采集设备信息</div>
          <div>
            <button class="button" @click="xinzenwangguan" style=" cursor: pointer;"><i class="el-icon-plus"></i> 新增网关</button>
            <!-- <button class="button" @click="$refs.biaoji.dialogVisible=true">新增采集表计</button> -->
            <button class="button" @click="tongxunbiaoji" style=" cursor: pointer;"><i class="el-icon-plus"></i> 新增通讯表计</button>
            <!-- 列表刷新 -->
            <el-tooltip class="item" effect="dark" content="刷新" placement="top">
                <span @click="shuaxin" style=" cursor: pointer;"><i class="el-icon-refresh-right"></i></span>
              </el-tooltip>
              <!-- 调节表格密度 -->
              <el-dropdown trigger="click" @command="command">
              <span class="el-dropdown-link">
                <el-tooltip class="item" effect="dark" content="密度" placement="top">
                <span class="item" style=" cursor: pointer;"><i class="el-icon-d-caret"></i></span>
              </el-tooltip>
              </span>
              <el-dropdown-menu slot="dropdown" >
                <el-dropdown-item command="默认">默认</el-dropdown-item>
                <el-dropdown-item command="中等">中等</el-dropdown-item>
                <el-dropdown-item command="紧凑">紧凑</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </div>
        <!-- 表格区域 -->
        <div class="tablebox" >
          <template>
          <el-table
            :data="tableData"
            border
            :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
            height="calc(100% - 1px)"
            :size="iissize"
            row-key="deviceId"
            v-loading="loading"
            :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
            >
            <el-table-column
              type="index"
              label="序号"
              fixed
              width="50">
            </el-table-column>
            <el-table-column
              prop="deviceType"
              label="设备类型"

             width="130">
             <template #default="{row}">
              <span :style="{'margin-left':row.children?.length?'':'23px'}">
                <img style="width: 16px;height: 16px;vertical-align: middle;" v-if="row.deviceType=='Gateway'" src="../../assets/bianyaqi/asseta/wulianwangguan.png" alt="">
                <img style="width: 16px;height: 16px;vertical-align: middle;" v-else-if="row.deviceType=='Meter'" src="../../assets/bianyaqi/asseta/dianbiao.png" alt="">
                <img style="width: 16px;height: 16px;vertical-align: middle;" v-else src="../../assets/bianyaqi/asseta/GPRSdianbiao.png" alt="">
                {{ row.deviceType=='Meter'?'表计':row.deviceType=='CommMeter'?'通讯表计':row.deviceType=='Gateway'?'网关':'' }}
              </span>
             </template>
            </el-table-column>
            <el-table-column
              prop="deviceName"
              label="设备名称"
              width="150">
            </el-table-column>
            <el-table-column
              prop="channelTag"
              label="采集通道"
              width="180">
              <template #default="{row}">
               <span>{{tongdaolist.filter(ele=>ele.value== row.channelTag)[0]?.text }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="gatewayName"
              label="采集网关"
              width="150">
            </el-table-column>
            <el-table-column
              prop="deviceTag"
              label="设备地址"
              width="150">
            </el-table-column>
            <el-table-column
              prop="iotStatus"
              label="运行状态"
              width="120">
              <template #default="{row}">
                <span>
                  <img style="width: 16px;height: 16px;vertical-align: middle;" v-if="row.iotStatus==1" src="../../assets//bianyaqi//asseta/zaixian.png" alt="">
                  <img style="width: 16px;height: 16px;vertical-align: middle;" v-else src="../../assets//bianyaqi//asseta/lixian.png" alt="">
                  {{ row.iotStatus==-1?'未激活':row.iotStatus==1?'在线':'离线' }}
                </span>
              </template>
            </el-table-column>
            <el-table-column
              prop="enabled"
              label="是否启用">
              <template #default="{row}">
                <!-- <span style="margin-right: 20px;">{{ row.enabled?'是':'否' }}</span> -->
                <span><el-switch  active-color="#13ce66" v-model="row.enabled" @change="changeswitch(row)"></el-switch></span>
              </template>
            </el-table-column>
            <el-table-column
              prop="createTime"
              label="创建日期"
              width="200">
            </el-table-column>
            <el-table-column
              label="操作"
              fixed="right"
              width="320"
              >
              <template #default="{row}">
                <el-button type="text" @click="gongkuang(row)">工况</el-button>
                <el-button type="text" @click="bianji(row)">编辑</el-button>
                <el-button type="text" @click="dellist(row)">删除</el-button>
                <el-button type="text" @click="fuzhi(row)">复制</el-button>
                <el-button v-show="row.deviceType=='Gateway'" type="text" @click="xinbiaoji(row)">新增表计</el-button>
                <el-button type="text" @click="bangding(row)">绑定信息</el-button>
              </template>
            </el-table-column>
          </el-table>
        </template>
        </div>
        <!-- <div class="fenye">
          <el-pagination
                background
                layout="prev, pager, next"
                :current-page.sync="pageobj.page"
                :page-size="20"
                @current-change="getlist"
                :total="+totalCount">
              </el-pagination>
        </div> -->
        <!-- 新增网关弹框 -->
          <WangGuan ref="wangguan" :biaojiobj="biaojiobj" 
          @shuaxin="shuaxin" :qufenbianji="qufenbianji" 
          @bianji="qufenbianji=''" :companyNo="companyNo"
          :fuzhinewupobj="fuzhinewupobj"
          @fuzhi="fuzhinewupobj={}"></WangGuan>
          <!-- 新增表计弹框 -->
          <BiaoJi ref="biaoji" :biaojiobj="biaojiobj"
           @shuaxin="shuaxin" :qufenbianji="qufenbianji" 
           @bianji="qufenbianji=''" :fuzhinewupobj="fuzhinewupobj"
           @fuzhi="fuzhinewupobj={}"></BiaoJi>
          <!-- x新增通讯表计 -->
          <TongXunbiao ref="tongxunbiao" @shuaxin="shuaxin"
           :biaojiobj="biaojiobj" :qufenbianji="qufenbianji"
            @bianji="qufenbianji=''" :companyNo="companyNo"
            :fuzhinewupobj="fuzhinewupobj" :orgName="orgName"
            @fuzhi="fuzhinewupobj={}"></TongXunbiao>
      </div>
      <!-- 查看绑定信息 -->
      <div>
        <el-dialog
          title="查询绑定设备信息"
          :visible.sync="dialogVisible"
          width="40%">
          <div>
            <el-table
            border
            :header-cell-style="{'text-align':'center',background:'#f5f5f5'}"
            height="calc(100% - 1px)"
            v-loading="loadingbangding"
            :data="tableDatabangding"
            style="width: 100%">
            <template slot="empty">
                <el-empty description="暂无数据"></el-empty>
              </template>
            <el-table-column
              type="index"
              label="序号"
              width="70">
            </el-table-column>
            <el-table-column
              label="企业">
              <template #default="{row}">
                <span>{{ treelist.filter(ele=>ele.orgNo==row.companyNo)[0]?.orgName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              prop="deviceName"
              label="设备名称">
            </el-table-column>
            <el-table-column
              prop="deviceId"
              label="设备Id">
            </el-table-column>
          </el-table>
          </div>
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisible = false" style="width:60px;height:30px;">取 消</el-button>
          </span>
        </el-dialog>
      </div>
      <!-- 工况信息 -->
      <GongKuang :treevalue="treevalue" ref="GongKuang"></GongKuang>
    </div>
  </div>
</template>

<script>
import {getKeywordListApi} from '@/api/Ledger'
import {getgenjieapi, getyewuzhuzhiapi} from '@/api/prwpaid/configura/ccb'
import {getleftlistapi,gettongdaoxialaapi,gettablelistapi,deletwulianapi,postqiyongapi,postjingyongapi,getguanlianshebeiapi,getNewCompanyTreeapi} from '@/api/iot'
import { color } from 'echarts';
import GongKuang from './GongKuang.vue'
import {getloginuserapi} from '@/api/cycle'
import WangGuan from '@/views/iot/wangguan.vue'
import BiaoJi from '@/views/iot/biaoji.vue'
import TongXunbiao from '@/views/iot/tongxun.vue'

export default {
  name: 'CallPoliceIndex',
  components: {
    WangGuan,
    BiaoJi,
    TongXunbiao,
    GongKuang
   },
  data() {
    return {
      dialogVisible:false,
      isshow: false,
      treevalue:{},
      isheight:80,
      number:90,
      num:100,
      textvalue:'',
      treelist: [],
      form:{},
      orgName: '',
      tongdaolist: [],
      tableData: [],
      pageobj: {
        page: 1,
        pageSize:10000
      },
      companyNo: '',
      totalCount: '',
      loading: false,
      iissize: 'medium',
      biaojiobj: {},
      qufenbianji: '',
      fuzhinewupobj: {},
      tableDatabangding:[],
      loadingbangding:false,
      props: {
        label: 'bizOrgName',
        disabled: 'disabled',
        children:'childList'
      },
      array:[]
    };
  },
  async mounted() {
    const loading = this.$loading({
      lock: true,
      text: 'loading',
      spinner: 'el-icon-loading',
      target: this.$refs.TreeBoxrefs
    })
    const { data:{entity} } = await getNewCompanyTreeapi()
    this.array = [entity]
    loading.close()
    const login = await getloginuserapi()
    const res = await getleftlistapi()
    if (login.data.entity.orgType == '04') {
      this.treelist = res.data.list.filter(ele => ele.orgNo == login.data.entity.orgNo)
      this.orgName = this.treelist[0].orgName
    } else {
      this.treelist = res.data.list
      this.orgName = res.data.list[0].orgName
    }
    const  ress= await gettongdaoxialaapi()
    this.tongdaolist = ress.data.list
    this.companyNo = this.treelist[0].companyNo
    // this.getlist(this.treelist[0].companyNo)
  },

  methods: {
    // 获取表格数据
    async getlist(id) {
      this.loading = true
      console.log(this.companyNo,666);
      
      const {data:{totalCount,list}} = await gettablelistapi({page:this.pageobj.page-1,pageSize:this.pageobj.pageSize,...this.form,companyNo:this.companyNo})
            this.totalCount = totalCount
      // 创建一个空数组，用于存储最终的树形结构数据
      const treeData = [];
      // 遍历原始数组，将网关和通讯表计分别存储到不同的数组中
      const gateways = list.filter(device => device.deviceType === 'Gateway');
      const commMeters = list.filter(device => device.deviceType === 'CommMeter');
      // 遍历网关数组，为每个网关添加对应的表计数据到 children 数组中
      gateways.forEach(gateway => {
        gateway.children = list.filter(device => device.gatewayId === gateway.deviceId && (device.deviceType === 'Meter' || device.deviceType === 'CommMeter'));
      });
      // 将网关数组添加到最终的树形结构数据中
      treeData.push(...gateways, ...commMeters);
      this.tableData = treeData
      // 输出结果
      // console.log(this.tableData,gateways,commMeters,treeData);
      this.loading = false
    },
    // 工况信息
    gongkuang(row) {
      this.treevalue = row
      this.$refs.GongKuang.dialogVisible=true
      this.$refs.GongKuang.getshebeilist(row.deviceId)
    },
    // 查看绑定信息
    async bangding(row) {
      this.dialogVisible = true
      this.loadingbangding=true
      const { data: { list } } = await getguanlianshebeiapi({ deviceId: row.deviceId })
      this.tableDatabangding = list
      this.loadingbangding=false
    },
    // 重置搜索栏
    chongzhi() {
      this.form = {}
      this.getlist(this.companyNo)
    },
    // 左侧树节点点击
    attree(item) {
      console.log(item);
      
      this.orgName=item.bizOrgName
      this.companyNo=item.bizOrgNo
      this.getlist(item.companyNo)
    },
    // 刷新
    shuaxin() {
      this.getlist(this.companyNo)
      this.$message.success('列表刷新成功')
    },
        // 折叠导航栏面板
        zedie() {
      this.isshow = !this.isshow
      if (this.isshow) {
        this.isheight = 140
        this.number=150
      } else {
        this.isheight = 80
        this.number=90
      }
    },
    //  调节表格密度
    command(val) {
      if (val === '默认') {
        this.iissize = 'medium'
      } else if (val === '中等') {
        this.iissize = 'small'
      } else {
        this.iissize = 'mini'
      }
    },
    submit() {
      this.getlist(this.companyNo)
    },
    // 编辑修改
    bianji(row) {
      if (row.deviceType=='CommMeter') {
        this.$refs.tongxunbiao.dialogVisible = true
        this.biaojiobj = {...row}
        this.qufenbianji='bianjizhuangtai'
      } else if (row.deviceType=='Meter') {
        this.$refs.biaoji.dialogVisible = true
        this.biaojiobj = {...row}
        this.qufenbianji='bianjizhuangtai'
      } else if (row.deviceType=='Gateway') {
        this.$refs.wangguan.dialogVisible = true
        this.biaojiobj = {...row}
        this.qufenbianji='bianjizhuangtai'
      }
    },
    xinbiaoji(row) {
        this.$refs.biaoji.dialogVisible=true
      this.biaojiobj = row
    },
    // 复制
    fuzhi(row) {
      this.$message.success('复制成功')
      this.fuzhinewupobj=row
    },
    // 列表修改禁用启用
    async changeswitch(val) {
      console.log(val);
      if (val.enabled) {
        await postqiyongapi({deviceId:val.deviceId})
      } else {
        await postjingyongapi({deviceId:val.deviceId})
      }
      this.shuaxin()
    },
    tongxunbiaoji() {
      this.$refs.tongxunbiao.dialogVisible = true
    },
    xinzenwangguan() {
      this.$refs.wangguan.dialogVisible=true
    },
    dellist (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await deletwulianapi({ deviceId: row.deviceId })
        this.getlist(this.companyNo)
      this.$message.success('删除成功')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
       // 树节点过滤
    filterNode(value, data) {
      if (!value) return true
      return data.bizOrgName.indexOf(value) !== -1
    },
  },
  watch: {
    textvalue(val) {
        this.$refs.tree.filter(val);
      }
  }
};
</script>

<style lang="scss" scoped>
*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
.active{
// : left;
  background-color: #f1f1f1;
}
.dengji{
        padding-left: 10px;
      }
.bigbox{
  padding: 10px;
  background-color: #f1f1f1;
  width: 100%;
  height: 100%;
  display: flex;
  .leftbox{
    width: 280px;
    height: 100%;
    background-color: #fff;
    padding: 20px;
    margin-right: 10px;
    .input{
      margin-bottom: 10px;
    }
    .listbox{
      height: calc(100% - 40px);
       overflow: auto;

      .little{
        padding: 5px 0;
        cursor: pointer; 
        font-size: 14px;
        color: #606266;
      }
    }
  }
  .rightbox{
     flex: 1;
     width: 0;
     .topbox{
      width: 100%;
      height: 80px;
      background-color: #fff;
      padding:0 20px;
      // line-height: 80px;
      padding-top: 18px;
      margin-bottom: 10px;
      .button{
        width: 63px;
        height: 32px;
        border: none;
        background-color: #1890ff;
        border-radius: 3px;
        color: #fff;
        margin-top: 3px;
      }
      .button{
        width: 63px;
        height: 32px;
        margin-right: 5px;
        background-color: #fff;
        border: 1px solid #ccc;
        border-radius: 3px;
        cursor: pointer;
      }
      .chaxun{
        background-color: #1890ff;
        color: #fff;
      }
      .shou{
        color: #1890ff;
        border: none;
        background-color: #fff;
      }
     }
     .buttombox{
      background-color: #fff;
      width: 100%;
      // height:calc(100% - 90px);
      padding: 20px;
      .text{
        display: flex;
        justify-content: space-between;
        .button{
          height: 32px;
          border: none;
        background-color: #1890ff;
        border-radius: 3px;
        color: #fff;
        padding: 0 5px;
        margin-left: 10px;
        }
        .item{
          margin-left: 10px;
        }
      }
        .tablebox{
          height: 94%;
          margin-top: 10px;
        }
      .fenye{
        text-align: right;
        margin-bottom: 5px;
      }
     }
  }
}
// ::v-deep .el-form{
//   width: 100%;
//   display: flex;
//   justify-content: space-between;
//   flex-wrap: wrap;
// }
// ::v-deep .el-form-item{
//   width: 24%;
//   flex-shrink: 0;
// }
::v-deep .el-col-5{
  text-align:right;
}
.el-form .el-col-6:nth-of-type(4),  .el-form .el-col-6:last-of-type::v-deep {
  /* 在这里添加你想要修改的样式 */
  text-align:right;
}

</style>